package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.entity.TradeRecord;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.mvc.PageView;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.TradeRecordService;
import net.starwifi.duobao.utils.ExcelUtils;
import net.starwifi.duobao.utils.times.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Administrator on 2016/1/25.
 */
@Controller("adminTradeRecordController")
@RequestMapping("/tradeRecord")
public class TradeRecordController extends BaseController {


    @Autowired
    TradeRecordService tradeRecordService;

    @Autowired
    MemberService memberService;
    @Autowired
    private ServletContext servletContext;

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageView pageView, ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        addDefaultFilter(pageView);
        pageView.addOrder(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        model.addAttribute("currentDate",format.format(new Date()));
        Date beginData= DateTool.setHms(new Date(), 0, 0, 0);
        Date endData= DateTool.setHms(new Date(),23,59,59);
        model.addAttribute("beginData", beginData);
        model.addAttribute("endData", endData);
        model.addAttribute("amount", tradeRecordService.getSumBigDecimal(pageView.getFilters(),"fee"));
        model.addAttribute("page", tradeRecordService.getScrollData(pageView));
        return "/tradeRecord/list";
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("types", tradeRecordService.find(id));
        return "/tradeRecord/edit";
    }


    /**
     * 宝币赠送
     */
    @RequestMapping(value = "/giving", method = RequestMethod.GET)
    public String giving(ModelMap model) {
        return "/tradeRecord/giving";
    }

    @RequestMapping(value = "/givingsave", method = RequestMethod.POST)
    public String givingsave(ModelMap model, MultipartFile file,BigDecimal fee,String remarks,String outSn) {
        List<Map<String,Object>>  lists = new ArrayList<Map<String, Object>>();
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
        try {
              list= ExcelUtils.readExcel(file);

            //查询用户id
            for (Map map :list){
                String mobile = map.get("mobile").toString();
                Member member = memberService.findByMobile(mobile);
                if (member !=null){
                    if (!member.getIsEnabled()) {
                        map.put("bak","账户已禁用");
                        lists.add(map);
                    }else{
                        TradeRecord tradeRecord=  tradeRecordService.findByoutSn(member.getId(), outSn);
                        if(tradeRecord!=null){
                            map.put("bak","重复用户");
                            lists.add(map);
                        }else{
                            tradeRecordService.adminRecharge(member.getId(), fee, remarks, outSn);
                        }
                    }


                }else{
                    //创建新的用户
                    member = new Member();
                    member=new Member();
                    member.setUsername("m" + mobile);
                    String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
                    member.setSalt(salt);
                    member.setMobile(mobile);
                    member.setIsEnabled(true);
                    member.setIsLocked(false);
                    member.setLoginFailureCount(0);
                    member.setLockedDate(null);
                    member.setBalance(BigDecimal.ZERO);
                    member.setCurrencyBalance(BigDecimal.ZERO);
                    member.setVirtualCurrency(BigDecimal.ZERO);
                    memberService.save(member);
                    if(member.getId()!=null){
                        TradeRecord tradeRecord=  tradeRecordService.findByoutSn(member.getId(), outSn);
                        if(tradeRecord!=null){
                            map.put("bak","重复用户，不能充值");
                            lists.add(map);
                        }else{
                            tradeRecordService.adminRecharge(member.getId(), fee, remarks, outSn);
                            map.put("bak","未注册用户，成功注册，充值正常");
                            lists.add(map);
                        }
                    }else{
                        map.put("bak","用户异常，未注册成功");
                        lists.add(map);
                    }

                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        model.addAttribute("number", list.size());//号码
        model.addAttribute("nonumber", lists.size());//未成功号码
        model.addAttribute("lists", lists);//未成功号码

        //addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "/tradeRecord/giving";
    }


//    public static List<String> importCsv(String filePath){
//        List<String> dataList=new ArrayList<String>();
//        BufferedReader br=null;
//        try {
//            br = new BufferedReader(new FileReader(new File(filePath)));
//            String line = "";
//            while ((line = br.readLine()) != null) {
//                dataList.add(line);
//            }
//        }catch (Exception e) {
//        }finally{
//            if(br!=null){
//                try {
//                    br.close();
//                    br=null;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        return dataList;
//    }


    /**
     * 导出Excel
     * */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public String  exportExcel(PageView pageView,HttpServletRequest request,ModelMap model) throws IOException {
        pageView.filterQuery(request);
        pageView.getOrders().add(Order.desc("id"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String url=tradeRecordService.exportExcel2003WithUsermodel(format.format(new Date()), servletContext.getRealPath("/"), pageView);
        model.addAttribute("message","Excel生成成功");
        model.addAttribute("content","<a href='/"+url+"' target=\"_blank\">点击下载</a>");
        return "/common/handle";
    }


}
